<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

    {% load static %}
    <link rel="shortcut icon" href="{% static 'img/seed.ico'%}" type="image/x-icon"/>
    <title>玉溪烟草发芽识别系统</title>
    <style>
        .main {width:100%;
               background:#eeeeee;}

        #file {
           /* position: absolute;*/
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            opacity: 100;
            /*display: none;*/
        }
        .main button {
            width: 100%;
            height: 100%;
            line-height: 30px;
            margin:5px
        }

        #show {width: 100%;}

    </style>
    {% load static %}
    <script src="{% static 'js/axios.min.js' %}"></script>
    <script src="{% static 'js/jquery-1.11.1.min.js' %}"></script>
</head>
<body>
<div id="main" class="main">
    <button id="capture">手机拍照</button>
    <form method="post" enctype="multipart/form-data" action="../upload2/" id="myForm">
        {% csrf_token %}
        <input id="file" type="file" accept="image/*" capture="user" name="file"/>
        <button type="button" id="upload">提交表单识别</button>
        <button type="button" id="uploadAjax">Ajax识别</button>
        <button type="button" id="testAjax">测试JSON</button>
    </form>

    <form method="post" action="../upload2/">
        {% csrf_token %}
        <input type="text" name="user" value="tom" placeholder="用户名"/>
        <input type="text" name="pass" value="123" placeholder="密码"/>
        <input type="submit" value="提交upload2"/>
    </form>

    <form method="post" action="../testCall/">
        {% csrf_token %}
        <input type="submit" value="提交测试"/>
    </form>
</div>
<div id="showRet">return</div>
<div id="showDetect">return2</div>

<!-- 用于处理图像大小 -->
<canvas id="show" class="used-for-changing-photo-size" width="200"></canvas>
<script>
        window.addEventListener("load", () => {
            let $submit = document.querySelector("#upload");//上传识别按钮
            $submit.onclick = function(){
                let form = document.querySelector("#myForm");
                form.submit();
            };

			//Ajax异步提交种子图片，并显示结果
			let btnn = document.querySelector('#uploadAjax');
            btnn.onclick = function(){
            	console.log('uploadAjax');
            	var csrf = $('#myForm input[name="csrfmiddlewaretoken"]').val();
            	$form = document.querySelector('#myForm');
                let dataForm = new FormData()
                dataForm.append('csrfmiddlewaretoken', csrf)
                dataForm.append('file', $form.file.files[0]);
              
                axios.post("../upload2/",
                         dataForm, {headers: { "Content-Type": "multipart/form-data"}})
                    .then(function (response) {
                        result = response.data;
                        document.querySelector('#showDetect').innerHTML = result;
                    })
                    .catch(function (error) {
                        console.log(error);
                });            	
            };
		

            let btn = document.querySelector('#testAjax');
            btn.onclick = function(){
                console.log('aaaaaaaa');
                var csrf = $('#myForm input[name="csrfmiddlewaretoken"]').val();

                /*
                $.ajax({
                    url: '../upload2/',
                    type: 'post',
                    data:{'user': 'jack', 'pass': '12345678', 'csrfmiddlewaretoken':csrf},
                    success: function(args){
                        $('#showRet').html(args);
                    }
                });
                //*/
                $form = document.querySelector('#myForm');
                let dataForm = new FormData()
                dataForm.append('user', 'jack')
                dataForm.append('pass', '12345678')
                dataForm.append('csrfmiddlewaretoken', csrf)
                dataForm.append('file', $form.file.files[0]);

                //axios.post("../upload2/",
                axios.post("../upload/",
                           dataForm, {headers: { "Content-Type": "multipart/form-data"}})
                    .then(function (response) {
                        result = response.data;
                        document.querySelector('#showRet').innerText = result;
                    })
                    .catch(function (error) {
                        console.log(error);
                });

                /*
                axios({url: "../upload2/",
                       method: 'post',
                       data: dataForm,
                       headers: { "Content-Type": "multipart/form-data"}})
                    .then(function (response) {
                        result = response.data;
                        document.querySelector('#showRet').innerText = result;
                    })
                    .catch(function (error) {
                        console.log(error);
                });
                //*/
            };

            //let $cap = document.querySelector("#capture");
            //$cap.onclick = function(){
                console.log('1111');
                const $camera = document.querySelector("#file");
                // 部分机型默认设置会不生效，需要手动再赋值
                $camera.setAttribute("capture", "user");
                $camera.onchange = handleTakePhoto;
            //}

            function handleTakePhoto(e) {
                // 读取照片
                if (this.files && this.files[0]) {
                    const fileData = this.files[0],
                    fileReader = new FileReader();
                    // 转化为base64
                    fileReader.readAsDataURL(fileData);

                    fileReader.onload = (e) => {
                        /*
                        changePhotoSize(fileReader.result).then(res => {
                            const $img = document.querySelector(".img-container img");
                            $img !== null && ($img.src = res);
                        }).catch(e => { })
                        */
                        changePhotoSize(fileReader.result).catch(e => { })
                    };
                }
            }

            /**
             * 调整照片大小
             * @param {string} imgData
             */
            function changePhotoSize(imgData) {
                const $canvas = document.querySelector("#show"),
                context = $canvas.getContext("2d"),
                image = new Image(),
                // 设置目标宽度（高度随原比例变化）
                targetWidth = 480;
                let aspectRatio = 1;

                image.src = imgData;
                console.log(11111);
                return new Promise((resolve, reject) => {
                	console.log('2222222');
                    image.onload = function () {
                        let divWidth = document.querySelector('#main').offsetWidth;
                        /*
                        aspectRatio = (this.height / this.width).toFixed(3);

                        if (divWidth > this.width) {
                            this.height = aspectRatio * divWidth;
                            this.width = divWidth;
                        }//*/

                        //
                        //this.height = aspectRatio * targetWidth;
                        //this.width = targetWidth;
                        $canvas.setAttribute("width", this.width + "px");
                        $canvas.setAttribute("height", this.height + "px");
                        context.drawImage(this, 0, 0, this.width, this.height);
                        resolve($canvas.toDataURL());

                        console.log('3333333');
                        console.log(this.width);
                        console.log(this.height);
                    };
                    image.onerror = (e) => {
                        reject(e);
                    };
                });
            }
        });

</script>
</body>
</html>